package com.xnx3.banmahuishou.qishouApplet.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.ObjectUtils;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.xnx3.DateUtil;
import com.xnx3.banmahuishou.core.entity.LotteryRecord;
import com.xnx3.banmahuishou.core.entity.MoneyChangeRecord;
import com.xnx3.banmahuishou.core.entity.Qishou;
import com.xnx3.banmahuishou.core.entity.ScoreChangeRecord;
import com.xnx3.banmahuishou.core.entity.Wangge;
import com.xnx3.banmahuishou.core.entity.WithdrawalLog;
import com.xnx3.banmahuishou.core.util.AppUtil;
import com.xnx3.banmahuishou.qishouApplet.vo.OrderGoodsListVO;
import com.xnx3.banmahuishou.qishouApplet.vo.OrderGoodsMapListVO;
import com.xnx3.banmahuishou.qishouApplet.vo.OrderListVO;
import com.xnx3.banmahuishou.qishouApplet.vo.TaskListVO;
import com.xnx3.j2ee.entity.System;
import com.xnx3.j2ee.entity.User;
import com.xnx3.j2ee.service.SqlService;
import com.xnx3.j2ee.util.ActionLogUtil;
import com.xnx3.j2ee.util.AttachmentUtil;
import com.xnx3.j2ee.util.ConsoleUtil;
import com.xnx3.j2ee.util.Page;
import com.xnx3.j2ee.util.Sql;
import com.xnx3.j2ee.vo.BaseVO;
import com.xnx3.j2ee.vo.UploadFileVO;
import com.xnx3.wangmarket.shop.core.entity.GoodsType;
import com.xnx3.wangmarket.shop.core.entity.Order;
import com.xnx3.wangmarket.shop.core.entity.OrderAddress;
import com.xnx3.wangmarket.shop.core.entity.OrderGoods;
import com.xnx3.weixin.applet.login.entity.WeixinAppletUserOpenid;
import com.xnx3.weixin.weixinPay.v2.MchPay;



/**
 * 骑手端--订单相关
 * @author qyw
 */
@RestController
@RequestMapping("/qishouApplet/task")
public class TaskController extends BaseController{


    @Resource
    private SqlService sqlService;

    /**
     * 任务中心--查询订单列表
     * @param type	 1新任务(服务中)；2已逾期，3历史订单 
     */
    @PostMapping("/getQishouOrderList.json")
    public OrderListVO getQishouOrderList(HttpServletRequest request,
        @RequestParam(value = "type",required = true,defaultValue = "1") Integer type) {

        // 订单状态 1待接单；2待取货，3已完成，4已取消
        OrderListVO vo = new OrderListVO();

        int userId = getUserId();
        if (userId == 0) {
            vo.setBaseVO(BaseVO.FAILURE, "请先登录");
            return vo;
        }
        Sql sql = new Sql(request);
        sql.appendWhere("qishou_id = " + userId);
        int nowTime = DateUtil.timeForUnix10();
        if (type == 1) {
            // 状态是待取货 且 还未超过预约时间
            sql.appendWhere("state = 2 AND reserve_end_time >= " + nowTime);
            sql.setDefaultOrderBy("reserve_start_time ASC");
        }
        if (type == 2) {
            // 状态是待接单  或者 状态是待取货 且 已超过预约时间
            sql.appendWhere("(state = 1 OR (state = 2 AND reserve_end_time < " + nowTime + "))");
            sql.setDefaultOrderBy("reserve_start_time ASC");
        }
        if (type == 3) {
            // 状态是已完成 或者 已取消
            sql.appendWhere("(state = 3 OR state = 4 OR state = 5)");
            sql.setDefaultOrderBy("reserve_start_time DESC");
        }

        //查询数据表的记录总条数。
        int count = sqlService.count("shop_order", sql.getWhere());
        //创建分页，并设定每页显示15条
        Page page = new Page(count, 15, request);
        //创建查询语句，只有SELECT、FROM，原生sql查询。其他的where、limit等不用写，代码会自动拼接
        sql.setSelectFromAndPage("SELECT * FROM shop_order", page);
        List<Order> list = sqlService.findBySql(sql, Order.class);
        List<TaskListVO> taskList = new ArrayList<TaskListVO>();
        // 获取订单相对应的地址信息
        for (Order order : list) {
            TaskListVO taskListVO = new TaskListVO();
            taskListVO.setOrder(order);
            OrderAddress orderAddress = sqlService.findById(OrderAddress.class, order.getId());
            taskListVO.setOrderAddress(orderAddress);
            taskList.add(taskListVO);
        }

        vo.setPage(page);
        vo.setList(taskList);
        ActionLogUtil.insert(request, userId, "获取骑手--任务中的订单列表 :" + list.toString());
        return vo;
    }





    /**
     * 获取骑手--任务中订单下的商品列表
     * @param orderId	 订单ID
     */
    @RequestMapping(value = "/getQishouOrderGoodsSumList.json",method = RequestMethod.POST)
    public OrderGoodsMapListVO getQishouOrderGoodsSumList(HttpServletRequest request,@RequestParam(value = "orderId",required = true,defaultValue = "0") Integer orderId) {

        OrderGoodsMapListVO vo = new OrderGoodsMapListVO();

        int userId = getUserId();
        if (userId == 0) {
            vo.setBaseVO(BaseVO.FAILURE, "请先登录");
            return vo;
        }
        String sqlString = "SELECT SUM(min_weight) minWeight,SUM(max_weight) maxWeight,SUM(min_money) minMoney,SUM(max_money) maxMoney,goods_type_name,goods_type_id"
            + "FROM shop_order_goods WHERE orderid = " + orderId + " GROUP BY goods_type_id,goods_type_name";
        List<Map<String,Object>> list = sqlService.findMapBySqlQuery(sqlString);
        // 遍历取出所有的大分类的id
        StringBuffer buffer = new StringBuffer("0");
        for (Map<String, Object> map : list) {
            buffer.append("," + map.get("goods_type_id"));
        }
        // 查询取出的大分类的信息,取图标
        sqlString = "SELECT * FROM shop_goods_type WHERE id IN(" + buffer + ")";
        List<GoodsType> goodsTypes = sqlService.findBySqlQuery(sqlString, GoodsType.class);
        for (GoodsType goodsType : goodsTypes) {
            for (Map<String, Object> map : list) {
                if (ObjectUtils.equals(map.get("goods_type_id"), goodsType.getId())) {
                    map.put("icon", goodsType.getIcon());
                }
            }
        }
        vo.setList(list);
        ActionLogUtil.insert(request, userId, "获取骑手--任务中订单下的商品列表 :" + list.toString());
        return vo;
    }
    /**
     * 获取骑手--任务中订单下的商品实际情况列表
     * @author zxy
     * @param orderId	 订单ID
     * @return 实际商品数据列表
     */
    @RequestMapping(value = "/getQishouOrderGoodsActualList.json",method = RequestMethod.POST)
    public OrderGoodsListVO getQishouOrderGoodsActualList(HttpServletRequest request,
        @RequestParam(value = "orderId",required = true,defaultValue = "0") Integer orderId) {

        OrderGoodsListVO vo = new OrderGoodsListVO();
        //获取登录用户的id
        int userId = getUserId();
        if (userId == 0) {
            vo.setBaseVO(BaseVO.FAILURE, "请先登录");
            return vo;
        }
        String sqlString = "SELECT * FROM shop_order_goods WHERE orderid = " + orderId ;
        List<OrderGoods> list= sqlService.findBySqlQuery(sqlString,OrderGoods.class);
        vo.setList(list);
        //日志记录
        ActionLogUtil.insert(request, userId, "获取骑手--任务中订单下的商品实际情况列表 :" + list.toString());
        return vo;
    }



    /**
     * 骑手端---去支付 标记该订单为已完成（线上支付）
     * @param orderId	 订单ID
     * @throws Exception 
     */
    @Transactional
    @PostMapping("/overOrder.json")
    public BaseVO overOrder(HttpServletRequest request,@RequestParam(value = "orderId",required = true,defaultValue = "0") Integer orderId) throws Exception {
        int userId = getUserId();
        User qsUser = sqlService.findById(User.class, userId);
        if (qsUser == null) {
            return notLogin();
        }
        Qishou qishou = sqlService.findById(Qishou.class, userId);
        if (qishou == null) {
            return notLogin();
        }
        Order order = sqlService.findById(Order.class, orderId);
        if (order == null) {
            return error("订单错误");
        }
        if (!"2".equals(order.getState())) {
            return error("订单状态错误, 请联系客服人员");
        }
        if ("3".equals(order.getState()) || "5".equals(order.getState())) {
            return error("订单已完成, 不可重复操作");
        }
        if (order.getQishouId() - userId != 0) {
            return error("该订单不属于你,无权操作");
        }
        String sqlString = "SELECT * FROM shop_order_goods WHERE orderid = " + orderId;
        List<OrderGoods> list = sqlService.findBySqlQuery(sqlString, OrderGoods.class);
        for (OrderGoods orderGoods : list) {
            if (orderGoods.getImage() == null) {
                return error("您有商品没拍照,请去拍照上传");
            }
        }

        // 总金额,分
        Integer payMoney = 0;
        // 总重量,g
        Integer payWeight = 0;
        for (OrderGoods orderGoods : list) {
            payMoney += orderGoods.getMoney();
            payWeight += orderGoods.getNumber();
        }
        // 给订单设置真实付款金额和总重量
        order.setPayMoney(payMoney);
        order.setAllWeight(payWeight);
        //找出订单归属的用户
        User user = sqlService.findById(User.class, order.getUserid());
        // 获取该骑手所属的网格
        Wangge wangge = sqlService.findById(Wangge.class, qishou.getWanggeUserid());

        // 判断骑手今日金额限制
        BaseVO baseVO = isUpLimit(request, qishou, payMoney,wangge);
        if (baseVO.getResult() == 0) {
            String infoJe = baseVO.getInfo();
            // 日志
            ActionLogUtil.insertUpdateDatabase(request,user.getId(), "付款失败","订单信息: " + order.toString());
            ConsoleUtil.info(infoJe);
            return error(infoJe);
        }

        // 这里就已经确认订单了, 所以要进行支付, 支付成功了 在进行成功后的下列操作, 支付不成功则返回不成功的信息
        com.xnx3.BaseVO basevo = wxPayToUser(request,user,order,wangge);
        //接收付款的消息 进行判断
        int result = basevo.getResult();
        if(result == 0) {
            String info = basevo.getInfo();
            // 日志
            ActionLogUtil.insertUpdateDatabase(request,user.getId(), "付款失败","订单信息: " + order.toString());
            ConsoleUtil.info(info);
            return error(info);
        }
        // 线上支付
        order.setIsLine(1);
        //付款成功 将该订单设为已完成 再进行保存
        order.setState("3");
        order.setPayTime(DateUtil.timeForUnix10());
        //付款成功之后再保存
        sqlService.save(order);

        // 给骑手添加 总出售垃圾的重量 总的订单完成次数 总收入金额
        qsUser.setAllIncomeMone(qsUser.getAllIncomeMone() == null ? payMoney : qsUser.getAllIncomeMone() + payMoney);
        qsUser.setAllSellWgight(qsUser.getAllSellWgight() == null ? payWeight : qsUser.getAllSellWgight() + payWeight);
        qsUser.setAllOrderNumbe(qsUser.getAllOrderNumbe() == null ? 1 : qsUser.getAllOrderNumbe() + 1);
        sqlService.save(qsUser);

        if (qishou != null) {
            qishou.setAllExpend(qishou.getAllExpend() == null ? payMoney : qishou.getAllExpend() + payMoney);
            qishou.setAllWgight(qishou.getAllWgight() == null ? payWeight : qishou.getAllWgight() + payWeight);
            qishou.setAllServiceNumb(qishou.getAllServiceNumb() == null ? 1 : qishou.getAllServiceNumb() + 1);
            sqlService.save(qishou);
        }
        // 给用户添加 总出售垃圾的重量 总的订单完成次数 总收入金额
        user.setAllIncomeMone(user.getAllIncomeMone() == null ? payMoney : user.getAllIncomeMone() + payMoney);
        user.setAllSellWgight(user.getAllSellWgight() == null ? payWeight : user.getAllSellWgight() + payWeight);
        user.setAllOrderNumbe(user.getAllOrderNumbe() == null ? 1 : user.getAllOrderNumbe() + 1);
        sqlService.save(user);
        //调用下单返积分方法
        xiaDanFanJF( request ,user,payMoney,orderId );
        //调用邀请新用户送积分方法
        yaoXinJiFen(request,user,order);
        //调用增加抽奖次数的方法
        chouJcs(request,user,order);
        ActionLogUtil.insert(request, userId, "骑手端--去支付（线上） 标记该订单为已完成,订单 :" + order.toString());
        return success("订单已完成,感谢使用斑马回收");
    }


    /**
     * 骑手端---去支付 标记该订单为已完成（线下支付）
     * @param orderId	 订单ID
     * @throws Exception 
     */
    @Transactional
    @ResponseBody
    @RequestMapping(value = "/overOrderXianxia.json",method = RequestMethod.POST)
    public BaseVO overOrderXianxia(HttpServletRequest request,@RequestParam(value = "orderId",required = true,defaultValue = "0") Integer orderId) throws Exception {
        int userId = getUserId();
        User qsUser = sqlService.findById(User.class, userId);
        if (qsUser == null) {
            return notLogin();
        }
        Qishou qishou = sqlService.findById(Qishou.class, userId);
        if (qishou == null) {
            return notLogin();
        }
        Order order = sqlService.findById(Order.class, orderId);
        if (order == null) {
            return error("订单错误");
        }
        if (!"2".equals(order.getState())) {
            return error("订单状态错误, 请联系客服人员");
        }
        if ("3".equals(order.getState()) || "5".equals(order.getState())) {
            return error("订单已完成, 不可重复操作");
        }
        if (order.getQishouId() - userId != 0) {
            return error("该订单不属于你,无权操作");
        }
        String sqlString = "SELECT * FROM shop_order_goods WHERE orderid = " + orderId;
        List<OrderGoods> list = sqlService.findBySqlQuery(sqlString, OrderGoods.class);
        for (OrderGoods orderGoods : list) {
            if (orderGoods.getImage() == null) {
                return error("您有商品没拍照,请去拍照上传");
            }
        }
        // 总金额,分
        Integer payMoney = 0;
        // 总重量,g
        Integer payWeight = 0;
        for (OrderGoods orderGoods : list) {
            payMoney += orderGoods.getMoney();
            payWeight += orderGoods.getNumber();
        }

        // 给订单设置真实付款金额和总重量
        order.setPayMoney(payMoney);
        order.setAllWeight(payWeight);

        //付款成功 将该订单设为已完成 再进行保存
        order.setState("3");
        order.setPayTime(DateUtil.timeForUnix10());
        // 线下支付
        order.setIsLine(0);
        //付款成功之后再保存
        sqlService.save(order);

        // 给骑手添加 总出售垃圾的重量 总的订单完成次数 总收入金额
        qsUser.setAllIncomeMone(qsUser.getAllIncomeMone() == null ? payMoney : qsUser.getAllIncomeMone() + payMoney);
        qsUser.setAllSellWgight(qsUser.getAllSellWgight() == null ? payWeight : qsUser.getAllSellWgight() + payWeight);
        qsUser.setAllOrderNumbe(qsUser.getAllOrderNumbe() == null ? 1 : qsUser.getAllOrderNumbe() + 1);
        sqlService.save(qsUser);
        if (qishou != null) {
            qishou.setAllExpend(qishou.getAllExpend() == null ? payMoney : qishou.getAllExpend() + payMoney);
            qishou.setAllWgight(qishou.getAllWgight() == null ? payWeight : qishou.getAllWgight() + payWeight);
            qishou.setAllServiceNumb(qishou.getAllServiceNumb() == null ? 1 : qishou.getAllServiceNumb() + 1);
            sqlService.save(qishou);
        }
        //找出订单归属的用户
        User user = sqlService.findById(User.class, order.getUserid());
        // 给用户添加 总出售垃圾的重量 总的订单完成次数 总收入金额
        user.setAllIncomeMone(user.getAllIncomeMone() == null ? payMoney : user.getAllIncomeMone() + payMoney);
        user.setAllSellWgight(user.getAllSellWgight() == null ? payWeight : user.getAllSellWgight() + payWeight);
        user.setAllOrderNumbe(user.getAllOrderNumbe() == null ? 1 : user.getAllOrderNumbe() + 1);
        sqlService.save(user);
        //调用下单返积分方法
        xiaDanFanJF( request ,user,payMoney,orderId );
        //调用邀请新用户送积分方法
        yaoXinJiFen(request,user,order);
        //调用增加抽奖次数的方法
        chouJcs(request,user,order);
        ActionLogUtil.insert(request, userId, "骑手端--去支付（线下） 标记该订单为已完成,订单 :" + order.toString());
        return success("订单已完成,请骑手小哥线下支付");
    }


    /**
     * 下单返积分 1：10
     * @param user	 下单用户
     * @param payMoney  支付的实际金额  单位 分
     * @param orderId 订单编号的id
     */
    public void xiaDanFanJF(HttpServletRequest request, User user , Integer payMoney ,Integer orderId) {
        int userid = user.getId();
        //将金额换算成元
        int trueMoney = payMoney / 100 ;
        //获取当前时间十位时间戳（后面赋值）
        Integer trueTime = DateUtil.timeForUnix10();
        Integer dateZero = DateUtil.getDateZeroTime(trueTime);//今日零点时间戳
        Integer dateNight = dateZero + 86400;//第二天零点时间戳
        //先计算该用户今日下单返已经获得了多少积分了
        String sql = "SELECT * FROM laji_score_change_record WHERE userid=" + userid + " AND type =" + ScoreChangeRecord.TYPE_XIADAN 
            + " AND add_time >=" + dateZero + " AND add_time <" + dateNight;
        List<ScoreChangeRecord> list = sqlService.findBySqlQuery(sql, ScoreChangeRecord.class);
        int highJiFen = 10000; //日上限10000积分
        int zongJiFen = 0;
        int bili = 10 ;// 一元换10积分 
        //如果用户今天还没有下单返积分的记录
        if(list.size() == 0) {
            //判断金额  如果大于等于一千 直接给10000积分
            if (trueMoney >= 1000) {
                //插入下单返产生的积分变动记录
                ScoreChangeRecord scoreChangeRecord = new ScoreChangeRecord();
                scoreChangeRecord.setUserid(userid);
                scoreChangeRecord.setAddTime(trueTime);
                scoreChangeRecord.setChangePoints(highJiFen);
                scoreChangeRecord.setType(ScoreChangeRecord.TYPE_XIADAN);
                scoreChangeRecord.setRemarks(DateUtil.intToString(trueTime, "yyyy-MM-dd HH:mm:ss") 
                    + user.getNickname() + "下单返了" + highJiFen + "积分,相关订单id为：" + orderId);
                scoreChangeRecord.setTitle("下单返积分");
                sqlService.save(scoreChangeRecord);
                //给用户积分余额加上下单返获得的积分
                Integer currency = user.getCurrency() < 0 ? 0 : user.getCurrency();
                user.setCurrency(currency + highJiFen);
                sqlService.save(user);
            }else {
                int Jifen = trueMoney * bili ;
                //插入下单返产生的积分变动记录
                ScoreChangeRecord scoreChangeRecord = new ScoreChangeRecord();
                scoreChangeRecord.setUserid(userid);
                scoreChangeRecord.setAddTime(trueTime);
                scoreChangeRecord.setChangePoints(Jifen);
                scoreChangeRecord.setType(ScoreChangeRecord.TYPE_XIADAN);
                scoreChangeRecord.setRemarks(DateUtil.intToString(trueTime, "yyyy-MM-dd HH:mm:ss") 
                    + user.getNickname() + "下单返了" + Jifen + "积分,相关订单id为：" + orderId);
                scoreChangeRecord.setTitle("下单返积分");
                sqlService.save(scoreChangeRecord);
                //给用户积分余额加上下单返获得的积分
                Integer currency = user.getCurrency() < 0 ? 0 : user.getCurrency();
                user.setCurrency(currency + Jifen);
                sqlService.save(user);
            }
        }else {
            //计算出已经下单返过的积分总数
            for (ScoreChangeRecord scoreChangeRecord : list) {
                zongJiFen = scoreChangeRecord.getChangePoints() + zongJiFen ;
            }
            //如果总积分小于10000 可以继续获得积分
            if (zongJiFen < highJiFen) {
                int Jifen = trueMoney * bili ;
                //求和
                int sumJiFen = Jifen + zongJiFen ;
                //判断这次积分跟之前积分的和是否小于等于10000
                if(sumJiFen <= highJiFen) {
                    //插入下单返产生的积分变动记录
                    ScoreChangeRecord scoreChangeRecord = new ScoreChangeRecord();
                    scoreChangeRecord.setUserid(userid);
                    scoreChangeRecord.setAddTime(trueTime);
                    scoreChangeRecord.setChangePoints(Jifen);
                    scoreChangeRecord.setType(ScoreChangeRecord.TYPE_XIADAN);
                    scoreChangeRecord.setRemarks(DateUtil.intToString(trueTime, "yyyy-MM-dd HH:mm:ss") 
                        + user.getNickname() + "下单返了" + Jifen + "积分,相关订单id为：" + orderId);
                    scoreChangeRecord.setTitle("下单返积分");
                    sqlService.save(scoreChangeRecord);
                    //给用户积分余额加上下单返获得的积分
                    Integer currency = user.getCurrency() < 0 ? 0 : user.getCurrency();
                    user.setCurrency(currency + Jifen);
                    sqlService.save(user);
                }else {
                    //如果积分的和大于了10000 则取差值加上
                    int shijiJiFen = highJiFen - zongJiFen;
                    //插入下单返产生的积分变动记录
                    ScoreChangeRecord scoreChangeRecord = new ScoreChangeRecord();
                    scoreChangeRecord.setUserid(userid);
                    scoreChangeRecord.setAddTime(trueTime);
                    scoreChangeRecord.setChangePoints(shijiJiFen);
                    scoreChangeRecord.setType(ScoreChangeRecord.TYPE_XIADAN);
                    scoreChangeRecord.setRemarks(DateUtil.intToString(trueTime, "yyyy-MM-dd HH:mm:ss") 
                        + user.getNickname() + "下单返了" + shijiJiFen + "积分,相关订单id为：" + orderId);
                    scoreChangeRecord.setTitle("下单返积分");
                    sqlService.save(scoreChangeRecord);
                    //给用户积分余额加上下单返获得的积分
                    Integer currency = user.getCurrency() < 0 ? 0 : user.getCurrency();
                    user.setCurrency(currency + shijiJiFen);
                    sqlService.save(user);
                }

            }
        }
        //日志插入
        ActionLogUtil.insertUpdateDatabase(request,"骑手完成订单-下单返积分");
    }

    /**
     * 邀请新用户送积分 
     * @param user 下单的用户
     * @param order 订单
     */
    public void yaoXinJiFen(HttpServletRequest request, User user,Order order) {
        //邀请新用户积分6666
        int yaoQingJiFen = 6666;
        //订单要求的金额10  转为分
        int money = 10 * 100; 
        // 判断用户的注册时间和下单时间是不是大于7天了， 是的话 直接不用管了， 小于7天的话 在往下进行逻辑
        int i = ( order.getAddtime() - user.getRegtime() ) / 86400 ;
        // 判断是否是新订单 是否小于7天，订单实际支付金额是否大于等于十块钱 
        if (i <= 7 && ( order.getIsNew() == 1 ) && order.getPayMoney() >= money) {
            //找出这个用户是否是被邀请过
            int referrerid = user.getReferrerid();
            //判断是否有邀请人的id
            if (referrerid > 0 ) {
                User trueUser = sqlService.findById(User.class, referrerid);
                Integer trueTime = DateUtil.timeForUnix10();
                //插入邀请新用户产生的积分变动记录
                ScoreChangeRecord scoreChangeRecord = new ScoreChangeRecord();
                scoreChangeRecord.setUserid(referrerid);
                scoreChangeRecord.setAddTime(trueTime);
                scoreChangeRecord.setChangePoints(yaoQingJiFen);
                scoreChangeRecord.setType(ScoreChangeRecord.TYPE_LAXIN);
                scoreChangeRecord.setRemarks(DateUtil.intToString(trueTime, "yyyy-MM-dd HH:mm:ss") 
                    + trueUser.getNickname() + "邀请新用户获得了" + yaoQingJiFen +"积分,相关订单id为：" + order.getId());
                scoreChangeRecord.setTitle("邀请新用户获得积分");
                sqlService.save(scoreChangeRecord);
                //给用户积分余额加上邀请新用户获得的积分
                Integer currency = trueUser.getCurrency() < 0 ? 0 : trueUser.getCurrency();
                trueUser.setCurrency(currency + yaoQingJiFen);
                sqlService.save(trueUser);
                //日志插入
                ActionLogUtil.insertUpdateDatabase(request,referrerid, "ID为" + referrerid + "的用户通过邀请新人获得积分");
            }
        }
    }




    /**
     * 抽奖次数
     * @param user 下单的用户
     * @param order 订单
     */
    public void chouJcs(HttpServletRequest request, User user,Order order) {
        int userid = user.getId();
        //获取当前时间十位时间戳（后面赋值）
        Integer trueTime = DateUtil.timeForUnix10();
        //今日零点时间戳
        Integer dateZero = DateUtil.getDateZeroTime(trueTime);
        //第二天零点时间戳
        Integer dateNight = dateZero + 86400;
        //单笔订单获得抽奖次数的门槛  默认100元 转分
        int money = 10000;
        String name = "LOTTERY_AMOUNT_SETTING";
        //将system表里对应的记录取出来
        System system = sqlService.findAloneByProperty(System.class, "name", name);
        // 如果记录存在 赋值给money 元转分
        if (system != null && system.getValue().length() != 0 ) {
            money = Integer.parseInt(system.getValue()) * 100;
        }
        int payMoney = order.getPayMoney();
        int cishu = user.getLotteryDrawCount();
        //如果到了可抽奖的门槛 
        if(payMoney >= money) {
            //先去判断抽奖记录表里有没有此用户的抽奖记录
            String sql = "SELECT * FROM laji_lottery_record WHERE userid=" + userid 
                + " AND add_time >=" + dateZero + " AND add_time <" + dateNight;
            List<LotteryRecord> list = sqlService.findBySqlQuery(sql, LotteryRecord.class);
            //如果抽奖记录表里抽奖记录小于3 
            int zongcishu = cishu + list.size();
            if (zongcishu < 3) {
                user.setLotteryDrawCount(cishu + 1);
                sqlService.save(user);
                //日志插入
                ActionLogUtil.insertUpdateDatabase(request,userid,"ID为" + userid + "的用户获得了一次抽奖");
            }
        }
    }



    /**
     * 骑手端--删除某订单下的某商品
     * @param orderGoodsId	 订单下的商品ID
     */
    @PostMapping("/deleteQishouOrderGoods.json")
    public BaseVO deleteQishouOrderGoods(HttpServletRequest request,@RequestParam(value = "orderGoodsId",required = true,defaultValue = "1") Integer orderGoodsId) {

        int userId = getUserId();
        if (userId == 0) {
            return error("请先登录");
        }
        OrderGoods orderGoods = sqlService.findById(OrderGoods.class, orderGoodsId);
        if (orderGoods == null) {
            return error("请选择要删除的商品");
        }
        sqlService.delete(orderGoods);
        // 日志
        ActionLogUtil.insert(request, userId, "骑手端--删除某订单下的某商品,删除的商品信息 :" + orderGoods.toString());
        return success();
    }



    /**
     * 骑手端---骑手确认物品时上传图片
     * @param multipartFile 图片文件
     * @author qyw
     */
    @RequestMapping(value="upImage.json", method= {RequestMethod.POST})
    public UploadFileVO upImage(HttpServletRequest request, @RequestParam("multipartFile") MultipartFile multipartFile){

        UploadFileVO vo = new UploadFileVO();
        int userid = getUserId();
        if(userid == 0){
            vo.setBaseVO(BaseVO.FAILURE, "请登录");
            return vo;
        }
        //将图片上传到 file/partner/ 路径下
        vo = AttachmentUtil.uploadFile("file/orderGoods/", multipartFile); 
        if (vo.getUrl() == null) {
            vo.setBaseVO(BaseVO.FAILURE, "上传图片失败");
            return vo;
        }
        // 记录日志
        ActionLogUtil.insertUpdateDatabase(request, userid, "骑手端---骑手确认物品时上传图片", "图片 :"+vo.getUrl()); 
        return vo;
    }




    /**
     * 判断骑手今日金额是否上限
     * @param qishou	骑手信息
     * @param payMoney	订单实际支付金额
     */
    public BaseVO isUpLimit(HttpServletRequest request, Qishou qishou ,Integer payMoney,Wangge wangge) throws Exception {

        // 判断该骑手所属的网格余额是否满足
        Integer wgMoney = wangge.getMoney();
        if (wgMoney - payMoney < 0) {
            return error("账户余额不足,请联系管理人员核实");
        }
        // 判断该笔订单金额是否超过网格给骑手设置的单笔金额上限
        Integer danQuota = qishou.getDanQuota();
        // 默认是0, 即网格没有设置金额上限
        if (danQuota <= 0) {
            // 微信官方默认设置是 单笔单日限额200元
            if (payMoney - 20000 > 0 ) {
                return error("单笔订单金额不能超过200元");
            }
        }else {
            if (payMoney - danQuota > 0) {
                return error("单笔订单金额不能超过" + danQuota/100 + "元");
            }
        }
        //该骑手的每天限额
        int qishouId = qishou.getId();
        int dayQuota = qishou.getDayQuota();
        // 当日零点的时间戳 
        int startTime = DateUtil.getDateZeroTime(DateUtil.timeForUnix10()); 
        // 次日零点的时间戳 
        int	endTime = startTime + 86400;
        if (dayQuota > 0) {
            //取出该骑手今日成功支付的订单 
            String sql = "SELECT * FROM shop_order WHERE pay_time >= " + startTime + " AND  pay_time < " + endTime + " AND qishou_id = " + qishouId
                + " AND ( state = " + Order.STATE_EVALUATED + " OR state = " + Order.STATE_FINISH + " )" + " AND is_line = 1 ";
            List<Order> list = sqlService.findBySqlQuery(sql, Order.class);
            //定义总金额 单位 分
            int moneySum = 0;
            if (list.size() > 0) {
                for (Order order :list) {
                    moneySum = moneySum + order.getPayMoney();
                }
            }
            // 已经完成支付的总金额 + 当前的
            int money = moneySum + payMoney ;
            //判断是否超过了该骑手的每日限额
            if (money > dayQuota) {
                return error("日支付总金额不能超过" + dayQuota/100 + "元");
            }
        }
        // 日志
        ActionLogUtil.insert(request,qishou.getId(), "判断骑手今日金额是否上限");
        return success();
    }



    /**
     * 骑手端--骑手进行支付(付款到零钱)
     * @param user 下单的用户
     * @param order 支付的订单
     * @throws Exception 
     */
    public BaseVO wxPayToUser(HttpServletRequest request, User user ,Order order,Wangge wangge) throws Exception {

        //TODO 这里后期看看需不需要添加synchronized锁
        //商户订单号，需保持唯一性 	32位订单号
        String partnerTradeNo = UUID.randomUUID().toString().replaceAll("-", "");
        partnerTradeNo = partnerTradeNo.substring(13) + DateUtil.timeForUnix13();
        //openid 用户openid，必填
        int userid = user.getId();
        WeixinAppletUserOpenid weixinAppletUserOpenid = sqlService.findAloneByProperty(WeixinAppletUserOpenid.class, "userid", userid);
        if(weixinAppletUserOpenid == null) {
            return error("该用户未绑定小程序");
        }
        String openid = weixinAppletUserOpenid.getOpenid();
        //付款金额，必填（单位：分）
        int money = order.getPayMoney();
        String amount = Integer.toString(money);
        // desc 付款备注，必填
        String desc = "回收垃圾获得金额";
        //deviceInfo 设备号，选填 （微信支付分配的终端设备号  这边我不知道这个参数去哪拿 暂时没设置）
        String deviceInfo = "";
        //微信商户付款至用户零钱
        MchPay mchPay = new MchPay(); 
        com.xnx3.BaseVO basevo =  mchPay.createMchPayOrder(partnerTradeNo, openid, amount, desc, deviceInfo);
        //判断付款是否成功
        int result = basevo.getResult();
        if(result == 0) {
            return error(basevo.getInfo());
        }
        //解析返回的xmlresult 获取微信付款单号
        String payId = MchPay.doXMLParse(basevo.getInfo()).get("payment_no");

        //新建付款记录  mysql单独建立一个表记录一份(laji_withdrawal_log)
        WithdrawalLog withdrawalLog = new WithdrawalLog();
        withdrawalLog.setOpenId(openid);
        withdrawalLog.setUserId(userid);
        withdrawalLog.setPhone(user.getPhone());
        withdrawalLog.setAmount(money);
        withdrawalLog.setAddTime(DateUtil.timeForUnix10());
        withdrawalLog.setPartnerTradeNo(partnerTradeNo);
        //微信付款单号 payment_no 付款成功，返回的微信付款单号 <payment_no><![CDATA[1000018301201505190181489473]]></payment_no>
        withdrawalLog.setPayId(payId);
        withdrawalLog.setQishouUserid(order.getQishouId());
        withdrawalLog.setQishouUsername(order.getQishouName());
        sqlService.save(withdrawalLog);
        //控制台打印 ConsoleUtil.log 记录一份
        ConsoleUtil.log("骑手付款到零钱, 用户ID " + userid + ", 付款记录: " + withdrawalLog.toString());
        // 日志
        ActionLogUtil.insertUpdateDatabase(request,userid, "骑手付款到零钱, 用户ID " + userid + ", 付款记录: " + withdrawalLog.toString());

        // 骑手支付完成, 给网格扣款, 添加账户流水记录
        Integer wgMoneyBefore = wangge.getMoney();
        Integer wgMoney = wgMoneyBefore - money;
        if (wgMoney < 0) {
            wgMoney = 0;
        }
        wangge.setMoney(wgMoney);
        sqlService.save(wangge);
        String string = "UPDATE user SET money = " + wgMoney + " WHERE id = " + wangge.getId();
        sqlService.executeSql(string);

        // 添加网格的金额变更记录
        MoneyChangeRecord wgChangeRecord = new MoneyChangeRecord();
        wgChangeRecord.setCreateTime(DateUtil.timeForUnix10());
        wgChangeRecord.setMoney(0 - money);
        wgChangeRecord.setPhone(wangge.getPhone());
        wgChangeRecord.setUserId(wangge.getId());
        wgChangeRecord.setUsername(wangge.getName());
        wgChangeRecord.setRemark("骑手【" + order.getQishouName() + "】付款到零钱给 【" + user.getNickname() + "】,付款之前网格余额为: "
            + AppUtil.doubleSplit((double)wgMoneyBefore/100) + "元, 之后为: " + AppUtil.doubleSplit((double)wangge.getMoney()/100) + "元, 骑手用户ID: " + order.getQishouId() + ", 收款用户ID: " + user.getId() + ", 付款记录ID: " + withdrawalLog.getId());
        sqlService.save(wgChangeRecord);

        // 添加骑手的金额变更记录
        MoneyChangeRecord qsChangeRecord = new MoneyChangeRecord();
        qsChangeRecord.setCreateTime(DateUtil.timeForUnix10());
        qsChangeRecord.setMoney(0 - money);
        qsChangeRecord.setPhone(order.getQishouPhone());
        qsChangeRecord.setUserId(order.getQishouId());
        qsChangeRecord.setUsername(order.getQishouName());
        qsChangeRecord.setRemark("骑手【" + order.getQishouName() + "】付款到零钱给 【" + user.getNickname() + "】,付款之前网格余额为: "
            + AppUtil.doubleSplit((double)wgMoneyBefore/100) + "元, 之后为: " + AppUtil.doubleSplit((double)wangge.getMoney()/100) + "元,  骑手用户ID: " + order.getQishouId() + ", 收款用户ID: " + user.getId() + ", 付款记录ID: " + withdrawalLog.getId());
        sqlService.save(qsChangeRecord);

        // 日志
        ActionLogUtil.insertUpdateDatabase(request,wangge.getId(), "网格余额变更","网格余额变更记录信息: " + wgChangeRecord.toString() + "骑手付款到零钱的提现记录: " + withdrawalLog.toString());

        return success();
    }


}
